package com.stores.action;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.stores.model.Brand;
import com.stores.model.Datastore;

public class ManageBrandAction {

	/**
	 * 
	 * @param category
	 */
	public void Create(Brand brand) {
		DatastoreService datastore = Datastore.get();
		Entity brandEntity = new Entity(Brand.class.getSimpleName());
		brandEntity.setProperty("name", brand.getName());
		brandEntity.setProperty("description", brand.getDescription());
		brandEntity.setProperty("manufacturerId", brand.getManufacturerId());	
		
		datastore.put(brandEntity);
	}

	/**
	 * 
	 * @param category
	 * @return
	 */
	public boolean Update(Brand brand) {
		DatastoreService datastore = Datastore.get();
		Query brandQuery = new Query(Brand.class.getSimpleName());
		brandQuery.addFilter(Entity.KEY_RESERVED_PROPERTY,
				FilterOperator.EQUAL, KeyFactory.createKey(
						Brand.class.getSimpleName(), brand.getId()));
		PreparedQuery query = datastore.prepare(brandQuery);
		Entity brandEntity = query.asSingleEntity();
		if (brandEntity == null) {
			return false;
		} else {
			brandEntity.setProperty("name", brand.getName());
			brandEntity.setProperty("description", brand.getDescription());
			brandEntity
					.setProperty("manufacturerId", brand.getManufacturerId());
			datastore.put(brandEntity);
		}
		return true;
	}

	/**
	 * 
	 * @return
	 */
	public List<Brand> Retrive() {
		DatastoreService datastore = Datastore.get();
		Query brandQuery = new Query(Brand.class.getSimpleName());
		PreparedQuery query = datastore.prepare(brandQuery);
		Iterable<Entity> brandEntities = query.asIterable();

		List<Brand> brands = new ArrayList<Brand>();

		for (Entity c : brandEntities) {
			Brand brand = new Brand();
			brand.setId(c.getKey().getId());
			brand.setName(c.getProperty("name").toString());
			brand.setDescription(c.getProperty("description").toString());
			brand.setManufacturerId(Long.parseLong(c.getProperty(
					"manufacturerId").toString()));
			brands.add(brand);
		}
		return brands;
	}

}
